/**
 * 
 */
package com.pos.net.request;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.pos.R;
import com.pos.net.base.AuthFailureError;
import com.pos.net.base.NetworkResponse;
import com.pos.net.base.Request.Method;
import com.pos.net.base.RequestQueue;
import com.pos.net.base.Response;
import com.pos.net.base.Response.ErrorListener;
import com.pos.net.base.Response.Listener;
import com.pos.net.base.VolleyError;
import com.pos.net.request.interfa.LoadListener;
import com.pos.net.request.load.MultiPartRequest;
import com.pos.net.toolbox.HttpHeaderParser;
import com.pos.net.toolbox.Volley;
import com.pos.set.AppSet;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:上传请求
 * @author cai
 * @time:2015年10月14日上午11:11:00
 */
public class UploadRequest {
	private static UploadRequest upLoadRequest;
	private Context mContext;
	/**
	 * 请求队列
	 */
	private static RequestQueue mRequestQueue;

	private UploadRequest(Context context) {
		mContext = context;
	}

	public synchronized static UploadRequest getInstance(Context context) {
		if (upLoadRequest == null) {
			upLoadRequest = new UploadRequest(context);
		}
		return upLoadRequest;
	}

	/**
	 * 开始上传(非文件列表)
	 * 
	 * @param url
	 *            上传请求url
	 * @param requestId
	 *            请求id
	 * @param params
	 *            请求的数据参数
	 * @param fileParams
	 *            请求的文件参数
	 * @param listener
	 *            文件上传监听事件
	 */
	public void startUpload(final String url, final int requestId, Map<String, String> params,
                            Map<String, String> fileParams, final LoadListener listener) {

		listener.onStart(requestId);
		// 网络不通，并且不是内网测试状态(即外网环境)
		if (!isNetworkOk(mContext) && !AppSet.testModel) {
			listener.onError(requestId, 0, mContext.getString(R.string.net_request_wrong));
		} else {

			MultiPartRequest<String> request = new MultiPartRequest<String>(Method.POST, url, new Listener<String>() {

				@Override
				public void onResponse(String response) {
					listener.onSuccess(requestId, url, response);
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					error.printStackTrace();
					listener.onError(requestId, 0, mContext.getString(R.string.net_request_fail));
				}
			}, new Response.LoadingListener() {

				@Override
				public void onLoading(long count, long current) {
					listener.onLoading(count, current);
				}
			}) {

				@Override
				protected Response<String> parseNetworkResponse(NetworkResponse response) {
					String parsed;
					try {
						parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
					} catch (UnsupportedEncodingException e) {
						parsed = new String(response.data);
					} catch (NullPointerException e) {
						parsed = "";
					}
					return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
				}

				@Override
				public Map<String, String> getHeaders() throws AuthFailureError {
					Map<String, String> headers = new HashMap<String, String>();
					headers.put("Charset", "UTF-8");
					// headers.putAll(requestInfo.getHeaders());
					return headers;
				}

			};

			if (params != null && params.size() != 0) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					request.addPart(entry.getKey(), entry.getValue());
				}
			}
			if (fileParams != null && fileParams.size() != 0) {
				for (Map.Entry<String, String> entry : fileParams.entrySet()) {

					String key = entry.getKey();
					String value = entry.getValue();

					if (!TextUtils.isEmpty(value))
						request.addPart(key, new File(value));
				}
			}
			request.setTag(this);
			getRequestQueue().add(request);
		}
	}

	/**
	 * 开始上传(文件列表)
	 * 
	 * @param url
	 *            上传请求url
	 * @param requestId
	 *            请求id
	 * @param params
	 *            请求的数据参数
	 * @param fileParams
	 *            请求的文件参数
	 * @param listener
	 *            文件上传监听事件
	 */
	public void startUploadList(final String url, final int requestId, Map<String, String> params, String filePartName,
                                List<String> filePathList, final LoadListener listener) {

		listener.onStart(requestId);
		// 网络不通，并且不是内网测试状态(即外网环境)
		if (!isNetworkOk(mContext) && !AppSet.testModel) {
			listener.onError(requestId, 0, mContext.getString(R.string.net_request_wrong));
		} else {

			MultiPartRequest<String> request = new MultiPartRequest<String>(Method.POST, url, new Listener<String>() {

				@Override
				public void onResponse(String response) {
					listener.onSuccess(requestId, url, response);
				}
			}, new ErrorListener() {

				@Override
				public void onErrorResponse(VolleyError error) {
					error.printStackTrace();
					listener.onError(requestId, 0, mContext.getString(R.string.net_request_fail));
				}
			}, new Response.LoadingListener() {

				@Override
				public void onLoading(long count, long current) {
					listener.onLoading(count, current);
				}
			}) {

				@Override
				protected Response<String> parseNetworkResponse(NetworkResponse response) {
					String parsed;
					try {
						parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
					} catch (UnsupportedEncodingException e) {
						parsed = new String(response.data);
					} catch (NullPointerException e) {
						parsed = "";
					}
					return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
				}

				@Override
				public Map<String, String> getHeaders() throws AuthFailureError {
					Map<String, String> headers = new HashMap<String, String>();
					headers.put("Charset", "UTF-8");
					// headers.putAll(requestInfo.getHeaders());
					return headers;
				}

			};

			if (params != null && params.size() != 0) {
				for (Map.Entry<String, String> entry : params.entrySet()) {
					request.addPart(entry.getKey(), entry.getValue());
				}
			}
			if (filePathList != null&&filePathList.size()!=0) {
				for (String fileName : filePathList) {
					request.addPart(filePartName, new File(fileName));
				}
			}
			request.setTag(this);
			getRequestQueue().add(request);
		}
	}

	/**
	 * 获取网络请求队列
	 */
	public RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(mContext);
		}
		return mRequestQueue;
	}

	/**
	 * 检验网络是否有连接，有则true，无则false
	 * 
	 * @param context
	 */
	public boolean isNetworkOk(Context context) {
		ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null && ni.isConnected()) {
			return true;
		}
		return false;
	}

}
